var data;
var display_level = ['', 'easy', 'medium', 'hard', 'random'];
//get login username
function getName(){
    var title = document.getElementById("title2");
    title.innerHTML = 'Quiz Record of ' + localStorage.getItem("UserName");
}
function search(date){
    localStorage.setItem('hdate',date);
    window.location.href = '../html/detail.html';
}

//show test details list
function getTable(){
    var details = data.detail;
    var htmlStr = "";
    
    for(var i = 0;i < details.length;i++) {
        var detail = details[i];
        htmlStr += "<tr>";
        htmlStr += "<td>" + detail.hdate + "</td>";
        htmlStr += "<td>" + detail.hcategory + "</td>";
        htmlStr += "<td>" + display_level[detail.hlevel] + "</td>";
        htmlStr += "<td>" + detail.hsize + "</td>";
        htmlStr += "<td>" + detail.hscore + "</td>";
        if(5 <= detail.htimelimit && detail.htimelimit <= 20){
            htmlStr += "<td>" + detail.htimelimit + "</td>";
        }else{
            htmlStr += "<td>" + "No time limit" + "</td>";
        }
        let tmpdate = String(detail.hdate);
        tmpdate = tmpdate.replace(/:/g, '').replace(/-/g, '').replace(/\s/g, '');
        htmlStr += "<td>" + '<button class="btn btn-info" type="button" onclick="search(' + tmpdate + ')">More information</button> '+ "</td>";
        htmlStr += "</tr>";
        }
    document.getElementById("tBody").innerHTML = htmlStr;
    document.getElementById("count").innerText = data.total;
}
window.onload = function(){
    function isLogin(){
        if(localStorage.hasOwnProperty("UserName")){
            document.getElementById("login").style.display = 'none';
            document.getElementById("login-out").style.display = 'block';
            document.getElementById("profile").style.display = 'block';
            document.querySelector("#profile a").innerHTML = 'User: ' + localStorage.getItem('UserName');
        }
        else{
            document.getElementById("login-out").style.display = 'none';
            document.getElementById("login").style.display = 'block';
            document.getElementById("profile").style.display = 'none';
        }
    }
    isLogin();
    function ok(){
        console.log(this.responseText);
        data = JSON.parse(this.responseText);
        getName();
        getTable();
    }
    function ko(){
        console.log(this.responseText);
        alert("Something error with gethistory");
    }
    ajaxRequest('../php/gethistory.php', 'get', null, ok, ko);
    

}